package acheng1314.cn.a3dbuild2;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.util.Log;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by pc859107393 on 2016/9/12 0012.
 */
public final class MyApplication extends Application {

    // 建立链表集合
    private List<Activity> activityList = new LinkedList<Activity>();
    private ArrayList<String> activityTmpNameList;  //临时库


    // 用单例模式，保证，这个ActivityManager 在整个应用中只有一个
    public static MyApplication instance;
    private boolean openLog = true;

    public void setOpenLog(boolean openLog) {
        this.openLog = openLog;
    }

    public MyApplication() {
    }

    public static MyApplication getInstance() {
        if (instance == null) {
            instance = new MyApplication();
        }
        return instance;
    }


    /**
     * 获取栈顶Activity（堆栈中最后一个压入的）
     */
    @SuppressWarnings("uncheded")
    public Activity getTopActivity() {
        Activity activity = activityList.get(activityList.size() - 1);
        return activity;
    }

    /**
     * 添加Activity到堆栈
     */
    @SuppressWarnings("uncheded")
    public void addActivity(Activity activity) {
        if (activityList == null) {
            activityList = new LinkedList<>();
        }
//        if (!findActivity(activity)) {  //查找不到当前需要添加到Activity管理栈的activity
        activityList.add(activity); //将当前Activity添加到管理栈
//        }
    }

    /**
     * 查找堆栈中是否存在activity  存在则true，不存在则false
     *
     * @param activity
     * @return
     */
    private boolean findActivity(Activity activity) {
        for (Activity mActivity : activityList) {
            if (activity.getLocalClassName().equals(mActivity.getLocalClassName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 结束栈顶Activity（堆栈中最后一个压入的）
     */
    @SuppressWarnings("uncheded")
    public void killTopActivity() {
        Activity activity = activityList.get(activityList.size() - 1);
        if (!activity.isFinishing()) {
            activity.finish();
            activityList.remove(activityList.size() - 1);   //从集合中拿掉最上面的activity
        }

    }

    /**
     * 结束指定的Activity
     */
    @SuppressWarnings("uncheded")
    public void killActivity(Activity activity) {
        if (activity != null) {
            for (int i = 0; i < activityList.size(); i++) {
                if (activity.getLocalClassName().equals(activityList.get(i).getLocalClassName())) {
                    activity.finish();
                    activityList.remove(i);
                }
            }
            activity = null;    //释放内存，可能在系统中回默认gc，但是我们强制指定后，能立即清理内存
        }
    }

    /**
     * 结束指定的Activity
     */
    @SuppressWarnings("uncheded")
    public boolean killOneActivity(String cls) {
        if (cls != null) {
            for (int i = 0; i < activityList.size(); i++) {
                if (cls.equals(activityList.get(i).getLocalClassName())) {
                    activityList.get(i).finish();
                    activityList.remove(i);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 结束指定类名的Activity
     */
    @SuppressWarnings("uncheded")
    public void killActivity(Class<?> cls) {
        for (Activity activity : activityList) {
            if (activity.getClass().equals(cls)) {
                killActivity(activity);
            }
        }
    }

    /**
     * 结束指定类名的Activity
     */
    @SuppressWarnings("uncheded")
    public void killtmpActivity() { //特殊用途，比如说缓存了多个Activity，需要在某刻关闭它们，才调用这个方法
        int i = 0;
        while (i < activityTmpNameList.size()) {
            if (killOneActivity(activityTmpNameList.get(i))) {
                i++;
            }
        }
        activityTmpNameList = null;
    }

    /**
     * 获取指定类名的Class
     */
    @SuppressWarnings("uncheded")
    public Class getClass(String className) {
        for (Activity activity : activityList) {
            if (activity.getLocalClassName().equals(className)) {
                return activity.getClass();
            }
        }
        return null;
    }

    public void putTmpActivityName(String activityName) {
        if (activityTmpNameList == null) {
            activityTmpNameList = new ArrayList<String>();
        }
        activityTmpNameList.add(activityName);
    }

    /**
     * 结束除栈顶以外的其他activity，使用场景：A需要打开B，同时关闭B以外的所有activity，则在B的onResume()中调用这个方法，参数为this
     *
     * @param activity 栈顶activity
     */
    public void killTopOtherActivity(Activity activity) {
        for (Activity mActivity : activityList) {
            if (activity.getLocalClassName().equals(mActivity.getLocalClassName())) {
                continue;   //跳出本次循环
            }
            if (!mActivity.isFinishing()) {
                mActivity.finish();
            }
        }
        activityList.clear();
        activityList.add(activity);
    }


    /**
     * 结束所有Activity
     */
    @SuppressWarnings("uncheded")
    public void killAllActivity() {
        for (Activity mActivity : activityList) {
            if (!mActivity.isFinishing()) {
                mActivity.finish();
            }
        }
        activityList.clear();
    }

    /**
     * 退出应用程序
     */
    @SuppressWarnings("uncheded")
    public void AppExit(Context context) {
        try {
            killAllActivity();
            // 杀掉，这个应用程序的进程，释放 内存
            int id = android.os.Process.myPid();
            if (id != 0) {
                android.os.Process.killProcess(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void outLog(String tag, String msg) {
        if (openLog) Log.i(tag, msg);
    }

}
